package com.yanyu.space.codegen.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yanyu.space.codegen.bean.po.DsSetting;
import com.yanyu.space.codegen.bean.vo.dssetting.DsSettingInfoVo;
import com.yanyu.space.codegen.bean.vo.dssetting.DsSettingSaveVo;
import com.yanyu.space.codegen.bean.vo.dssetting.DsSettingSearcheVo;
import com.yanyu.space.codegen.bean.vo.dssetting.TableInfoVo;
import com.yanyu.space.codegen.service.IDsSettingService;
import com.yanyu.space.common.core.bean.db.PageEntity;
import com.yanyu.space.common.core.bean.web.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 数据库配置 前端控制器
 *
 * @author yanyu
 * @date 2020/12/1
 */
@RestController
@RequestMapping("/codegen/dsSetting")
@Api(tags = "数据源配置")
@Validated
@AllArgsConstructor
public class DsSettingController {

    private IDsSettingService service;

    @GetMapping("/list")
    @ApiOperation(value = "查询数据源配置信息")
    public R list(DsSettingSearcheVo vo) {
        PageEntity<DsSettingInfoVo> page = service.listPage(vo);
        return R.ok(page);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询数据源配置信息")
    public R get(@PathVariable("id") Long id) {
        DsSetting dsSetting = service.getById(id);
        DsSettingInfoVo dsSettingInfoVo = new DsSettingInfoVo();
        BeanUtils.copyProperties(dsSetting, dsSettingInfoVo);
        return R.ok(dsSettingInfoVo);
    }

    @GetMapping("/check/nickName")
    @ApiOperation(value = "数据库昵称名字是否存在")
    public R checkName(Long id, @NotEmpty(message = "昵称为空") String nickName) {
        long cnt = service.count(Wrappers.<DsSetting>lambdaQuery().ne(id != null, DsSetting::getId, id).eq(DsSetting::getNickName, nickName));
        return R.ok(cnt);
    }

    @PostMapping
    @ApiOperation(value = "新增数据源配置")
    public R add(@RequestBody @Validated DsSettingSaveVo vo) {
        service.add(vo);
        return R.ok();
    }

    @PutMapping
    @ApiOperation(value = "修改数据源配置")
    public R update(@RequestBody @Validated DsSettingSaveVo vo) {
        service.update(vo);
        return R.ok();
    }

    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除数据源配置")
    public R delete(@PathVariable List<Long> ids) {
        service.removeByIds(ids);
        return R.ok();
    }

    @GetMapping("/test/{id}")
    @ApiOperation(value = "数据库连接测试")
    public R test(@PathVariable("id") Long id) {
        service.testDs(id);
        return R.ok();
    }

    @GetMapping("/list/ds/tables/{id}")
    @ApiOperation(value = "查询数据库下所有表结构")
    public R listDsTables(@PathVariable("id") Long dsId) {
        List<TableInfoVo> result = service.listDsTables(dsId);
        return R.ok(result);
    }
}

